<?php

class Rapide_Util_Captcha
{
	private
		$_aColours = array(),
		$_aFonts = array();

	public function __construct(array $aParameters = array())
	{
		$this->_aColours['background'] = '#ffffff';
		$this->_aColours['font']			 = '#333333';
		$this->_aColours['noise']			= '#aaaaaa';

		$sFontDir = _DIR_FONTS;
		$this->_aFonts = array($sFontDir . 'Arial.ttf', $sFontDir . 'Impact.ttf');

		foreach($this->_aFonts as $i => $sFont)
		{
			if(!file_exists($sFont))
			{
				unset($this->_aFonts[$i]);
			}
		}

		if(!count($this->_aFonts))
		{
			$sError = 'Correct font has not been specified';
			throw new Rapide_Util_Form_Token_Exception($sError);
		}
	}

	public function check($sToken)
	{
		$oSession = new Rapide_Session('token');
		$oSession->start();

		return $oSession->token == $sToken;
	}

	public function generate()
	{
		$sToken = $this->_generateUniqueToken();

		$this->_setToken($sToken);

		$iWidth	= strlen($sToken) * 15 + 10;
		$iHeight = 25;

		$rImage = imagecreate($iWidth, $iHeight);

		$rBackgroundColour = $this->_getColour($rImage, $this->_aColours['background']);
		$rFontColour			 = $this->_getColour($rImage, $this->_aColours['font']);
		$rNoiseColour			= $this->_getColour($rImage, $this->_aColours['noise']);
/*
		$aNoise = array();

		for($i = 0; $i < round($iWidth / 1.5); $i++)
		{
			$iX = rand(0, $iWidth);
			$iY = rand(0, $iHeight);

			$sCordinates = $iX . '-' . $iY;

			if(!in_array($sCordinates, $aNoise))
			{
				imageellipse($rImage, $iX, $iY, rand(2, 7), rand(3, 6), $rNoiseColour);
				$aNoise[] = $sCordinates;
			}
			else
				$i--;
		}
*/
		for($i = 0; $i < strlen($sToken); $i++)
		{
			imagettftext($rImage, rand(14, 16), rand(-15, 15), rand(3, 5) + $i * 15, 20 + rand(-3, 3), $rFontColour, $this->_aFonts[rand(0, count($this->_aFonts) - 1)], $sToken{$i});
		}

		header('Content-Type: image/jpeg');
		imagejpeg($rImage, null, 95);
	}

	private function _generateUniqueToken($iLength = 5)
	{
		$oRandom = new Rapide_Util_Random_String('1234567890'); //WERTYUOPASDFGHJKZXCBNM
		$sToken = $oRandom->generate($iLength);

		return $sToken;
	}

	private function _setToken($sToken)
	{
		$oSession = new Rapide_Session('token');

		$oSession->start();

		$oSession->token = $sToken;
	}

	private function _getColour($rImage, $sColour)
	{
		$sColour = substr($sColour, 1);

		$aRGB = array();

		for($i = 0; $i < 6; $i = $i + 2)
		{
			$aRGB[] = (int)hexdec($sColour{$i} . $sColour{$i + 1});
		}

		return imagecolorallocate($rImage, $aRGB[0], $aRGB[1], $aRGB[2]);
	}

}

?>